package com.cherrish.demo.bio;

import com.cherrish.demo.SocketConst;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author cherrish
 * @time 2019-04-26 15:40
 * @name BiooServer
 * @desc:
 */
public class BioServer {

    public static void main(String[] args) {
        start();
    }
    private static void start(){

        ServerSocket serverSocket = null;
        Socket socket = null;
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            serverSocket = new ServerSocket(SocketConst.PORT);
            serverSocket.setSoTimeout(20000);
            socket = serverSocket.accept();
            inputStream = socket.getInputStream();
            byte[] buff = new byte[1024];
            int len = inputStream.read(buff);
            System.out.println("recv from client: " + new String(buff, 0, len));

            outputStream = socket.getOutputStream();
            String response = "Hello, Client.";
            outputStream.write(response.getBytes(SocketConst.CHARSET));
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                outputStream.close();
                inputStream.close();
                socket.close();
                serverSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
